<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    html,body{margin: 0;padding:0;}
  </style>
</head>
<body>
  <canvas class="cvs"></canvas>
</body>
<script>

  const cvs = document.querySelector(".cvs");
  cvs.width = document.documentElement.clientWidth;
  cvs.height = document.documentElement.clientHeight;

  const ctx = cvs.getContext("2d");

  const maxNum = 600;

  let x1 = 100;
  let y1 = 200;

  let x2 = 400;
  let y2 = 400;

  // 绘制
  action();

  let speedX1 = random(5, -5);
  let speedX2 = random(5, -5);
  let speedY1 = random(5, -5);
  let speedY2 = random(5, -5);

  setInterval(()=>{
    x1 += speedX1;
    x2 += speedX2;
    y1 += speedY1;
    y2 += speedY2;
    // 边界限定
    if(x1 < 0){
      speedX1 = -speedX1;
    }
    if(x1 > cvs.width){
      speedX1 = -speedX1;
    }
    if(x2 < 0){
      speedX2 = -speedX2;
    }
    if(x2 > cvs.width){
      speedX2 = -speedX2;
    }
    if(y1 < 0){
      speedY1 = -speedY1;
    }
    if(y1 > cvs.height){
      speedY1 = -speedY1;
    }
    if(y2 < 0){
      speedY2 = -speedY2;
    }
    if(y2 > cvs.height){
      speedY2 = -speedY2;
    }
    // 绘制
    action();
  }, 30)


  function random(a,b){
    return Math.round(Math.random()*(a-b)+b);
  }



  function action(){
    ctx.clearRect(0, 0, cvs.width, cvs.height);
    // 画线
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);

    const a = x2-x1;
    const b = y2-y1;
    const now = Math.sqrt(a*a + b*b);
    // 计算线的透明度
    const opacity = now > maxNum ? 0 : (1 - now/maxNum);
    ctx.strokeStyle = `rgba(0,0,0,${opacity})`;
    ctx.stroke();
    // 端点1
    ctx.beginPath();
    ctx.arc(x1, y1, 6, 0, 2*Math.PI);
    ctx.fill();
    // 端点2
    ctx.beginPath();
    ctx.arc(x2, y2, 6, 0, 2*Math.PI);
    ctx.fill();
  }


  // 600  0
  // 300  0.5
  // 0  1
  // 1 - now / 600

</script>
</html>